package com.uboot.uyibai;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uboot.uyibai.core.exception.UBootException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * 翻译
 */
@Slf4j
public class FanyiV3Demo {

    private static final String YOUDAO_URL = "https://openapi.youdao.com/api";

    private static final String APP_KEY = "17f97a68a12b592b";

    private static final String APP_SECRET = "06UibnKptaHKqahgnJ4SuW8zm5fBrUMC";

    public static String fanyi(String q) throws IOException {
        String salt = String.valueOf(System.currentTimeMillis());
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        String signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET;
        String sign = getDigest(signStr);
        RequestBody formBody = new FormBody.Builder()
                .add("q", q)
                .add("from", "en")
                .add("to", "zh-CHS")
                .add("signType", "v3")
                .add("curtime", curtime)
                .add("appKey", APP_KEY)
                .add("salt", salt)
                .add("sign", sign)
                .build();
        /** 处理结果 */
        Response response = HttpUtils.post(YOUDAO_URL, formBody);
        if(response.body() != null){
            try{
                JSONObject jsonObject = (JSONObject) JSONObject.parse(response.body().string());
                if(jsonObject != null && 0 == jsonObject.getInteger("errorCode")){
                    JSONArray jsonArray = jsonObject.getJSONArray("translation");
                    if(jsonArray != null){
                        StringBuilder stringBuilder = new StringBuilder();
                        for (Object o : jsonArray) {
                            stringBuilder.append(o);
                        }
                        return stringBuilder.toString();
                    }
                }
            }catch (Exception e){
                throw new UBootException("翻译失败：" + e.getMessage());
            }
        }
        return null;
    }

    /**
     * 生成加密字段
     */
    public static String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
        try {
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
    *
    * @param result 音频字节流
    * @param file 存储路径
    */
    private static void byte2File(byte[] result, String file) {
        File audioFile = new File(file);
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(audioFile);
            fos.write(result);

        }catch (Exception e){
            log.info(e.toString());
        }finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

  public static String truncate(String q) {
        if (q == null) {
            return null;
        }
        int len = q.length();
        String result;
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }
}
